import UNI_APP from '@/.env.js'

// 请求队列
let requestList = [];
// 是否正在刷新中
let isRefreshToken = false;

const request = (options) => {
	const header = options.header || {};
	const loginInfo = uni.getStorageSync("token");
	if (loginInfo) {
		header.accessToken = loginInfo.accessToken;
	}
	return new Promise(function(resolve, reject) {
		uni.request({
			url: UNI_APP.BASE_URL + options.url,
			method: options.method || 'GET',
			header: {
				'token': uni.getStorageSync('token')
			},
			data: options.data || {},
			async success(res) {
				// console.log('resjjj===',res)
				// console.log('resxxx===',res)
				
				if (res.data.code == 0) {
					// console.log('11111===',res)
					
					return resolve(res.data.data)
				} else if (res.data.code == 400) {
					getApp().exit();
				} else if (res.data.code == 401) {
					console.log("token失效，尝试重新获取")
					if (isRefreshToken) {
						// 正在刷新token,把其他请求存起来
						requestList.push(() => {
							resolve(request(options))
						})
						return;
					}
					isRefreshToken = true;
					// 发送请求, 进行刷新token操作, 获取新的token
					const res = await reqRefreshToken();
					if(!res.code) {
						uni.setStorageSync('token',res.data.token)
						uni.setStorageSync('refreshToken',res.data.refreshToken)
						requestList.forEach(cb => cb());
						requestList = [];
						isRefreshToken = false;
						// 重新发送刚才的请求
						return resolve(request(options))
					}

				} else {
					uni.showToast({
						icon: "none",
						title: res.data.message,
						duration: 1500
					})
					return reject(res.data)
				}
			},
			fail(error) {
				uni.showToast({
					title: "网络似乎有点不给力，请稍后重试",
					duration: 1500
				})
				return reject(error)
			}
		});
	});
}


const reqRefreshToken = () => {
	return new Promise(function(resolve, reject) {
		const refreshToken = uni.getStorageSync('refreshToken')
		uni.request({
			method: 'POST',
			url: UNI_APP.BASE_URL + "/user/refreshToken?refreshToken=" + refreshToken,
			success: (res) => {
				console.log('res\\\\\\===',res)
				resolve(res.data);
			},
			fail: (res) => {
				reject(res);
			}
		});
	});
}

export default request;